<template>
    <div class="page-wrapper">
        <!-- 顶部操作栏 -->
        <div class="toolbar">
            <div class="left">
                <el-button type="primary" :icon="Plus" @click="goAdd">新增</el-button>
                <el-button :icon="Download">导出</el-button>
            </div>
            <div class="right">
                <el-input v-model="searchKeyword" placeholder="请输入计划单号/计划主题" clearable class="search-input"
                    @keyup.enter="handleSearch">
                    <template #suffix>
                        <el-icon class="clickable" @click="handleSearch">
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
            </div>
        </div>

        <!-- 列表 -->
        <el-table :data="tableData" border stripe v-loading="loading" height="520" style="width: 100%">
            <el-table-column type="selection" width="48" />
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="planCode" label="计划单号" width="180" align="center" />
            <el-table-column prop="planName" label="计划主题" min-width="220" show-overflow-tooltip align="center" />
            <el-table-column prop="planTime" label="单据日期" width="140" align="center">
                <template #default="{ row }">{{ formatDate(row.planTime) }}</template>
            </el-table-column>
            <el-table-column prop="itemOverview" label="物品概述" min-width="200" show-overflow-tooltip align="center" />
            <el-table-column prop="relatedItem" label="关联项目" width="140" align="center" />
            <el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip align="center" />
            <el-table-column label="操作" width="140" align="center" fixed="right">
                <template #default="{ row }">
                    <el-button link type="danger" @click="confirmDelete(row)">删除</el-button>
                    <el-button link type="primary" @click="openDetail(row)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <div class="total">共{{ pagination.totalCount }}项数据</div>
            <el-pagination background layout="sizes, prev, pager, next, jumper" :current-page="pagination.pageIndex"
                :page-size="pagination.pageSize" :page-sizes="[5, 10, 20, 30, 50]" :total="pagination.totalCount"
                @current-change="handlePageChange" @size-change="handleSizeChange" />
        </div>

        <!-- 详情抽屉 -->
        <el-drawer v-model="detailVisible" title="生产计划详情" size="60%">
            <div v-if="detail" class="detail-wrap">
                <el-descriptions :column="3" border size="small" class="mb16">
                    <el-descriptions-item label="计划单号">{{ detail.planCode }}</el-descriptions-item>
                    <el-descriptions-item label="计划主题">{{ detail.planName }}</el-descriptions-item>
                    <el-descriptions-item label="计划时间">{{ formatDateTime(detail.planTime) }}</el-descriptions-item>
                    <el-descriptions-item label="关联项目">{{ detail.relatedItem || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="备注">{{ detail.remark || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="附件">{{ detail.attachment || '-' }}</el-descriptions-item>
                </el-descriptions>

                <div class="sub-title">计划物品明细</div>
                <el-table :data="detail.planGoodsDetails || []" border stripe height="360">
                    <el-table-column type="index" label="序号" width="60" align="center" />
                    <el-table-column prop="goodsCode" label="物品编号" width="160" align="center" />
                    <el-table-column prop="goodsName" label="物品名称" min-width="180" show-overflow-tooltip
                        align="center" />
                    <el-table-column prop="goodsModel" label="物品规格" width="180" show-overflow-tooltip align="center" />
                    <el-table-column prop="goodsUnit" label="单位" width="100" align="center" />
                    <el-table-column prop="planGoodsCount" label="计划数量" width="120" align="center" />
                    <el-table-column prop="planGoodsUnitCount" label="主单位数量" width="120" align="center" />
                </el-table>
            </div>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Download } from '@element-plus/icons-vue'
import { MES_XSP_ApiHost } from '@/utils/Interceptors'
import { useRouter } from 'vue-router'

interface ListItem {
    productionPlanId: number
    planCode: string
    planName: string
    planTime: string
    itemOverview: string
    relatedItem: string
    remark: string
}

interface Paging<T> {
    code: number
    msg: string
    pageData: T[]
    totalCount: number
    totalPage: number
}

interface PlanGoodsDetailDTO {
    planGoodsId: number
    productionPlanId: number
    goodsId: number
    goodsCode: string
    goodsName: string
    goodsModel: string
    goodsUnit: string
    planGoodsCount: number
    planGoodsTime: string
    planGoodsUnitCount: number
    remark: string
}

interface DetailDTO {
    productionPlanId: number
    planCode: string
    planName: string
    salesId: number
    relatedItem: string
    planTime: string
    remark: string
    attachment: string
    createTime: string
    creator: string
    modifyTime?: string
    modifier?: string
    planGoodsDetails: PlanGoodsDetailDTO[]
}

const loading = ref(false)
const searchKeyword = ref('')
const tableData = ref<ListItem[]>([])
const pagination = reactive({ pageIndex: 1, pageSize: 10, totalCount: 0, totalPage: 0 })

const detailVisible = ref(false)
const detail = ref<DetailDTO | null>(null)

const router = useRouter()
const goAdd = () => { router.push({ path: '/ProductionPlanAdd' }) }

const fetchList = async () => {
    try {
        loading.value = true
        const params: any = {
            pageIndex: pagination.pageIndex,
            pageSize: pagination.pageSize
        }
        if (searchKeyword.value) {
            // 同时支持按单号与主题搜索，后端任一匹配即可
            params.planCode = searchKeyword.value
            params.planName = searchKeyword.value
        }
        const { data } = await MES_XSP_ApiHost.get<Paging<ListItem>>('/api/ProductionPlan/GetProductionPlanList', { params })
        if (data?.code === 200) {
            tableData.value = data.pageData || []
            pagination.totalCount = data.totalCount || 0
            pagination.totalPage = data.totalPage || 0
        } else {
            tableData.value = []
            pagination.totalCount = 0
            pagination.totalPage = 0
            ElMessage.error(data?.msg || '获取生产计划失败')
        }
    } catch (e: any) {
        tableData.value = []
        pagination.totalCount = 0
        pagination.totalPage = 0
        ElMessage.error(e?.message || '获取生产计划失败')
    } finally {
        loading.value = false
    }
}

const handleSearch = () => {
    pagination.pageIndex = 1
    fetchList()
}

const handlePageChange = (page: number) => {
    pagination.pageIndex = page
    fetchList()
}

const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.pageIndex = 1
    fetchList()
}

const openDetail = async (row: ListItem) => {
    try {
        const { data } = await MES_XSP_ApiHost.get<{ code: number; msg: string; data: DetailDTO }>(
            '/api/ProductionPlan/GetProductionPlanById',
            { params: { productionPlanId: row.productionPlanId } }
        )
        if (data?.code === 200) {
            detail.value = data.data
            detailVisible.value = true
        } else {
            ElMessage.error(data?.msg || '获取详情失败')
        }
    } catch (e: any) {
        ElMessage.error(e?.message || '获取详情失败')
    }
}

const confirmDelete = (row: ListItem) => {
    ElMessageBox.confirm(`确定删除生产计划「${row.planCode}」吗？`, '提示', {
        type: 'warning'
    }).then(async () => {
        try {
            const { data } = await MES_XSP_ApiHost.delete<{ code: number; msg: string; data: boolean }>(
                '/api/ProductionPlan/DeleteProductionPlan',
                { params: { productionPlanId: row.productionPlanId } }
            )
            if (data?.code === 200) {
                ElMessage.success('删除成功')
                fetchList()
            } else {
                ElMessage.error(data?.msg || '删除失败')
            }
        } catch (e: any) {
            ElMessage.error(e?.message || '删除失败')
        }
    }).catch(() => { })
}

const formatDate = (val?: string) => {
    if (!val) return '-'
    const d = new Date(val)
    if (isNaN(d.getTime())) return val
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

const formatDateTime = (val?: string) => {
    if (!val) return '-'
    const d = new Date(val)
    if (isNaN(d.getTime())) return val
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const da = String(d.getDate()).padStart(2, '0')
    const hh = String(d.getHours()).padStart(2, '0')
    const mm = String(d.getMinutes()).padStart(2, '0')
    const ss = String(d.getSeconds()).padStart(2, '0')
    return `${y}-${m}-${da} ${hh}:${mm}:${ss}`
}

onMounted(fetchList)
</script>

<style scoped>
.page-wrapper {
    padding: 20px;
    background: #fff;
}

.toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.left {
    display: flex;
    gap: 8px;
}

.right {
    display: flex;
    align-items: center;
}

.search-input {
    width: 260px;
}

.clickable {
    cursor: pointer;
}

.pagination {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 12px;
    padding: 12px 0;
}

.total {
    color: #666;
    font-size: 12px;
    margin-right: auto;
}

.mb16 {
    margin-bottom: 16px;
}

.sub-title {
    font-weight: 600;
    color: #333;
    margin: 6px 0 10px;
}

.detail-wrap {
    padding-right: 4px;
}
</style>
